package cn.edu.cdtu.yulei.test_demo.utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    //销毁
    public void destroy() { }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) resp;
        final String uri = request.getRequestURI();
        HttpSession session =request.getSession();

        // 设置字符编码过滤
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        if(session.getAttribute("user") == null){
			// 没有登陆进行拦截
            if(!uri.equals("/commService/") & !uri.contains("/register") & !uri.contains("/login")){
                response.sendRedirect("/commService");
                return;
            }
        }
        chain.doFilter(request, response);
    }

    //初始化
    public void init(FilterConfig config) throws ServletException { }
}